import { readFile, stat } from 'fs/promises'; // 使用 fs/promises 获得异步 API

import { marked } from 'marked';

import type { MarkedOptions } from 'marked';
import type { Plugin } from 'vite';

export default function markdownPlugin(options: MarkedOptions = {}): Plugin {
  marked.setOptions({
    breaks: options.breaks ?? false,
    gfm: options.gfm ?? true,
    pedantic: options.pedantic ?? false,
  });

  // 使用 Map 作为缓存，存储内容和最后修改时间
  const cache = new Map<string, { html: string; lastModified: number }>();

  return {
    name: 'vite:markdown',
    enforce: 'pre',

    async transform(_code, id) {
      if (!id.endsWith('.md')) return null;

      // 获取文件状态信息
      const stats = await stat(id);
      const lastModified = stats.mtimeMs;

      // 检查缓存
      const cached = cache.get(id);
      if (cached && cached.lastModified === lastModified) {
        return {
          code: `export default ${JSON.stringify(cached.html)}`,
          map: null,
        };
      }

      // 异步读取文件内容
      const content = await readFile(id, 'utf-8');

      // 解析 Markdown
      const html = await marked.parse(content);

      // 更新缓存
      cache.set(id, { html, lastModified });

      return {
        code: `export default ${JSON.stringify(html)}`,
        map: null,
      };
    },
  };
}
